package com.ziyun.erp.modules.member.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.ziyun.erp.common.e.DeleteEnum;
import com.ziyun.erp.modules.member.dao.UserWalletDao;
import com.ziyun.erp.modules.member.entity.UserCreditEntity;
import com.ziyun.erp.modules.member.entity.UserWalletEntity;
import com.ziyun.erp.modules.member.service.UserCreditService;
import com.ziyun.erp.modules.member.service.UserWalletService;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.Query;
import org.apache.commons.collections.map.HashedMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.Map;


@Service("userWalletService")
public class UserWalletServiceImpl extends ServiceImpl<UserWalletDao, UserWalletEntity> implements UserWalletService {

    @Autowired
    private UserCreditService userCreditService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        Page<UserWalletEntity> page = this.selectPage(
                new Query<UserWalletEntity>(params).getPage(),
                new EntityWrapper<UserWalletEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public boolean updateByMap(Map<String, Object> updateMap, Integer uId) {
        int update = this.baseMapper.updateByMap(updateMap, uId);
        if (update == 0){
            return false;
        }
        return true;
    }

    @Override
    public void recoveryCredit(BigDecimal receiveMoney, String orderId, Integer userId) {
        UserWalletEntity userWallet = this.selectById(userId);
        BigDecimal creditUse = userWallet.getCreditUse();
        creditUse = creditUse.add(receiveMoney);

        Map<String, Object> updateMap = new HashedMap();
        updateMap.put("creditUse", creditUse);
        this.baseMapper.updateByMap(updateMap, userId);

        UserCreditEntity userCredit = new UserCreditEntity();
        userCredit.setUserId(userId);
        userCredit.setCreditUse(creditUse);
        userCredit.setOrderId(Long.valueOf(orderId));
        userCredit.setMtime(new Date());
        userCredit.setDisabled(DeleteEnum.NOT_DELETE.toInt());
        userCredit.setMessage("确认收款后可用信用还原");
        userCredit.setMemo("订单【" + orderId + "】回款：" + receiveMoney + ",调整可用信用：" + receiveMoney);
        userCreditService.insert(userCredit);
    }

    @Override
    public int updatePointById(Integer userId, Integer point) {
        return this.baseMapper.updatePointById(userId,point);
    }

}
